package com.hong.spring.controller;

import lombok.extern.log4j.Log4j2;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: csh
 * @Date: 2020/12/11 18:51
 * @Description:
 */
@RestController
@RequestMapping("/zk")
@Log4j2
public class ZkController {
    @Autowired
    private ZooKeeper zk;

    /**
     *
     * 功能描述: 添加
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/12/11 19:16
     */
    @RequestMapping("/add")
    public String add(String node){
        if(StringUtils.isEmpty(node)){
            log.error("参数异常！");
            return "参数异常！";
        }
       try {
           node="/"+node;
           Stat stat = zk.exists(node,false);
           if(null==stat){
               //新建节点
               String createResult = zk.create(node,"hong".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
               System.out.println(createResult);
           }
           byte[] b = zk.getData(node,false,stat);
           log.info(new String(b));
       }catch (Exception e){
           e.printStackTrace();
           return "失败";
       }
       return  "成功";
    }
    /**
     *
     * 功能描述: 设置
     *
     * @param:
     * @return:
     * @auther: csh
     * @date: 2020/12/11 19:17
     */
    @RequestMapping("/set")
    public String add(String node,String val){
        if(StringUtils.isEmpty(node)){
            log.error("参数异常！");
            return "参数异常！";
        }
        try {
            node ="/"+node;
            Stat stat = zk.exists(node,true);
            if(null==stat){
                //新建节点
                log.error("设置失败!");
                return "设置失败!";
            }
            zk.setData(node, val.getBytes(), -1);
            byte[] b = zk.getData(node,true,stat);
            log.info(new String(b));
            return new String(b);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
